# encoding: utf-8
__author__ = 'zhengyong'

import os
import copy
import datetime
import sys
import json
from MyLibrary.ReadWriteExcel import ReadWriteExcel


read_excel = ReadWriteExcel()


class OperaLib(object):

	def read_config(self, file, sheet):

		self.file_path = file
		self.sheet = sheet
		row_count = read_excel.get_excel_row_count(self.file_path, self.sheet)
		self.col_A = "A"
		self.col_B = "B"
		self.start = 2

		name_list = read_excel.colname_read_excel_return_list(self.file_path, self.sheet, self.col_A,
																   self.start, row_count)
		value_list = read_excel.colname_read_excel_return_list(self.file_path, self.sheet, self.col_B,
																	self.start, row_count)
		config_name_value_dict = self.lists_to_dict(name_list, value_list)

		return config_name_value_dict

	def transform_data(self, change_str):
		# 如果excel里取下来的值是str格式，json解码转换成字典格式，并捕获异常
		if isinstance(change_str, str) or isinstance(change_str, str):
			try:
				change_dict = json.loads(change_str, encoding="utf-8")
			except Exception as ex:
				print(('ERROR: Parse change_str %s failed\nDetail: %s ' % (change_str, ex)))
				change_dict = {"error": str(ex)}

		# 如果excel里取下来的值是dict格式，则可以直接使用
		elif isinstance(change_str, dict):
			print("change_str is a dict, not the str")
			change_dict = copy.deepcopy(change_str)

		else:
			change_dict = {"error": "NotStrOrDict"}
			type1 = type(change_str)
			print(type1)

		return change_dict

	# 给list元素添加后缀，后缀名由posfix_num指定
	def add_list_posfix(self, list, posfix_num):
		new_list = [i + str(posfix_num) for i in list]

		return new_list

	# 将两个列表组成成字典
	def lists_to_dict(self, list1, list2):
		L1 = list1
		L2 = list2
		return dict(list(zip(L1, L2)))

	# 获取列表元素个数
	def get_list_count(self, list):
		count = len(list)
		return count

	# 获取字典长度
	def get_dict_count(self, dict):
		count = len(dict)
		return count

	# 获取元素类型
	def get_type(self, value):
		value_type = type(value)
		return value_type

	# 通过字典的值获取对应Key
	def get_dict_keys(self, d, val):
		return [k for k, v in list(d.items()) if v == val]

	# 生成区间数字列表
	def get_number_list(self, start, end):
		listID = list(range(int(start), int(end)))
		return listID

	# 创建空值字典
	def create_none_value_dict(self, lst):
		dict = {}
		dict1 = dict.fromkeys(lst)
		return dict1

	# 创建文件路径
	def make_dir(self, path):
		a = os.path.exists(path)
		if a:
			pass
		else:
			os.makedirs(path)

	# 生成区间数字列表
	def create_id_list(self, start, end):
		listID = list(range(int(start), int(end)))
		return listID

	# 将两个字典变量合并成一个新的字典
	def dicts_merge(self, dict1, dict2):
		newdict = {}
		for key in list(dict1.keys()):
			for value in list(dict2.values()):
				if key == value:
					ls = dict1[key]
					vkey = ls
					kvalue = self.get_keys(dict2, value)
					newdict[kvalue[0]] = str(vkey)
		return newdict
# 通过字典的值获取对应Key
	def get_keys(self, d, val):
		return [k for k, v in list(d.items()) if v == val]

	# 删除字典中不在给定列表中的key
	def del_dict_key_value(self, para_name_list, whole_para_name_value_dict):
		lst = para_name_list
		dict = whole_para_name_value_dict
		for k in list(dict.keys()):
			if k not in lst:
				dict.pop(k)
		return dict

	# 通过字典批量修改字典中key的值
	def update_dict(self, change_dict, to_change_dict):
		d1 = change_dict
		d2 = to_change_dict
		d2.update(d1)
		return d2

	# 依次修改字典中的每一个值
	def change_dict_values_each(self, changed_value, changed_key_list, to_change_dict):
		d1 = dict.fromkeys(changed_key_list, changed_value)
		d2 = to_change_dict
		alist = []
		for k1 in list(d1.keys()):
			d3 = copy.deepcopy(d2)
			d3[k1] = d1[k1]
			alist.append(d3)
		return alist

	# 依次修改字典中的每一个值-特殊字符
	def change_dict_values_each_special(self, changed_value, changed_key_list, to_change_dict):
		d1 = dict.fromkeys(changed_key_list, changed_value)
		d2 = to_change_dict
		data_list = []
		para_list = []
		for k1 in list(d1.keys()):
			d3 = copy.deepcopy(d2)
			d3[k1] = d1[k1]
			data_list.append(d3)
			para_list.append(k1)

		return data_list

	# 依次修改字典中的每一个值为空
	def change_dict_values_null_each(self, changed_key_list, to_change_dict):
		d1 = dict.fromkeys(changed_key_list)
		d2 = to_change_dict
		data_list = []
		for k1 in list(d1.keys()):
			d3 = copy.deepcopy(d2)
			d3[k1] = d1[k1]
			data_list.append(d3)

		return data_list

	# 获取自增1
	def plusPlus(self, num):
		plusnum = int(num)
		plusnum += 1
		return plusnum

	# 获取自增指定步长
	def plusPlus_num(self, num, plus_num):
		plusnum = int(num)
		plusnum += int(plus_num)
		return plusnum

	# 批量获取字典list中的key值并以list形式返回
	def get_dict_list_value_for_key(self, key, dict_list):

		value_list = []

		for i in range(len(dict_list)):
			value = dict_list[i][str(key)]
			value_list.append(value)

		return value_list

	# 批量获取字典list中的key值，并以二维list形式返回
	def get_dict_list_listvalue_for_key(self, key, dict_list):

		value_list = []

		for i in range(len(dict_list)):
			value = dict_list[i][str(key)]
			value= [value]
			value_list.append(value)

		return value_list

	# DB查询结果以字符串形式提取（一个结果）
	def get_string_from_tuple_of_db_back(self, tuple_from_db):

		if len(tuple_from_db) != 0:
			str_db = str(tuple_from_db[0][0])
			return str_db
		else:
			return "数据库返回为空"

	def str_split_by_input_char(self, str_name, char_name):

		str_splited_list = str_name.split(char_name)

		return str_splited_list

	def str_split_list(self, str_name):

		str_splited_list = str_name.split()

		return str_splited_list

	def db_datetime_to_date(self, datetimeinput):

		# datetime_list = datetime.split(" ")
		# date_u = ''.join(datetime_list[0])
		# date_str = date_u.encode('unicode-escape').decode('string_escape')

		date = datetime.datetime.strptime(str(datetimeinput)[:10], '%Y-%m-%d')

		return date

	#深度递归遍历更新dict
	def deepupdatedict(self,fromdict, todict):
		for key in list(fromdict.keys()):
			if key not in list(todict.keys()):
				todict[key] = fromdict[key]
			else:
				if isinstance(fromdict[key],dict) and isinstance(todict[key],dict):
					self.deepupdatedict(fromdict[key], todict[key])
				else:
					todict[key] = fromdict[key]
		return todict

#Just for test
if __name__ == '__main__':
	run = OperaLib()
	todict = {'certId': '2.30421198705e+17', 'realName': '\u738b\u660e\u94ed', 'sysSourceId': '\u4e07\u5361\u7cfb\u7edf', 'sourceUserId': '1147445233', 'sysUserId': '1147445233', 'apiKey': '475', 'timestamp': 1525661126332, 'data': {'trade_no': '20180507104525648000000387975411', 'code': '0', 'id_name': '\u738b\u660e\u94ed', 'id_no': '370782198705201121', 'fee': 'N', 'report_detail': {'latest_three_month': 49, 'query_cash_count': 0, 'apply_score': '531', 'query_org_count': 1, 'query_finance_count': 1, 'apply_credibility': '78', 'latest_six_month': 49, 'query_sum_count': 49, 'latest_query_time': '2018-05-03', 'latest_one_month': 18}, 'trans_id': 'h7Yp47gV7', 'desc': '\u67e5\u8be2\u6210\u529f'}, 'trans_id': 'h7Yp47gV7'}
	fromdict = {'data': {'report_detail': {'latest_three_month': '-20'}}}
	run.deepupdatedict(fromdict,todict)
	print(todict)
